package com.cn.longdistancebusstation.scenic.order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.PayResult;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.SubmitPftOrder;

import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/4/13.
 */

public class TicketOrderPaymentActivity extends BaseActivity implements View.OnClickListener{
    private static final int ALI_PAY_FLAG = 1;
    private String mOrderNo;
    private String strSendDate;
    private String strOrderPrice;
    private String strPftId;
    private String mScenicName;
    private String mTicketName;
    private Button btnPay;
    private String orderNote;
    private Map<String,String> params;
    private SubmitPftOrder mSubmitPftOrder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);
        getTitleTextView().setText("支付方式");
        Intent intent=getIntent();
        mOrderNo =intent.getStringExtra("orderNo");
        mScenicName =intent.getStringExtra("scenicName");
        mTicketName =intent.getStringExtra("ticketName");
        strOrderPrice=intent.getStringExtra("totalAmount");
        orderNote= mScenicName +"(" + mTicketName + "）";

        initView();
        btnPay.setText("确认支付"+"  "+"¥"+strOrderPrice+"元");
        registerBroadcast();


    }

    private void initView() {
        btnPay=(Button)findViewById(R.id.pay_orders);
        btnPay.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.pay_orders:
                pay();
                break;
        }

    }
    private void pay() {
        showHud();
        Retrofit retrofit = new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService = retrofit.create(HttpService.class);
        Call<Result<String>> call = httpService.getScenicEncryptOrderInfo("jingqu", strOrderPrice, orderNote, mOrderNo, mOrderNo);
        call.enqueue(new Callback<Result<String>>() {
            @Override
            public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                hideHud();
                Result result = response.body();
                if(result.getHead().getSuccess()){
                    //然后判断body里的flags是否都为true
                    String strEncryptOrderInfo = result.getBody().toString();
                    //
                    aliPay(strEncryptOrderInfo);
                }
                else{
                    Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<String>> call, Throwable t) {
                hideHud();
                Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void aliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(TicketOrderPaymentActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = ALI_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private Handler mHandler = new Handler(){
        public void handleMessage(Message message){
            switch (message.what){
                case ALI_PAY_FLAG:
                {
                    PayResult payResult = new PayResult((Map<String, String>) message.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(TicketOrderPaymentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setAction("close_current_boundary");
//                        sendBroadcast(intent);
                        Intent in=new Intent(TicketOrderPaymentActivity.this,ScenicOrderDetailsActivity.class);
                        in.putExtra("orderId",strPftId);
                        //startActivity(in);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(TicketOrderPaymentActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            }
        }
    };
    MyReceiver receiver;
    private void registerBroadcast() {
        // 注册广播接收者
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("close_current_boundary");
        this.registerReceiver(receiver,filter);
    }
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("close_current_boundary")){
                finish();
            }
        }
    }

}
